package pathx

import (
	"errors"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	"gitee.com/zhongguo168a/gocodes/gox/osx"
)

// GetWorkingPath 获取当前文件执行的路径
func GetWorkingPath() string {
	file, _ := exec.LookPath(os.Args[0])

	//得到全路径，比如在windows下E:\\golang\\test\\a.exe
	path, _ := filepath.Abs(file)

	rst := filepath.Dir(path)

	return rst
}

func S生成不重复的文件路径(path string) (string, error) {
	count := 0
	最后的目录 := ""
	ext := filepath.Ext(path)
	name := strings.Replace(filepath.Base(path), ext, "", 1)

	re := regexp.MustCompile(`(.*)_\d+$`)
	if re.MatchString(name) {
		results := re.FindAllStringSubmatch(name, -1)
		name = results[0][1]
	}

	dir := filepath.Dir(path)
	dir = filepath.ToSlash(dir)
	for {

		if count == 0 {
			最后的目录 = path
		} else {
			最后的目录 = dir + "/" + name + "_" + strconv.Itoa(count) + ext
		}

		has, oserr := osx.Exists(最后的目录)
		if oserr != nil {
			return "", oserr
		}
		if has {
			count++
			continue
		}
		break
	}

	return 最后的目录, nil
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

// GetGoPackagePath 获取当前文件执行的路径
func GetGoPackagePath(pkg string) (goPath, pkgPath string, err error) {
	gopath := os.Getenv("GOPATH")
	arr := strings.Split(gopath, ";")
	for _, val := range arr {
		goPath = val
		pkgPath = val + "/src/" + pkg
		if PathExists(pkgPath) == true {
			return
		}
	}

	err = errors.New("not found")
	return
}

// FormatPath 格式化路径, 统一转换为linux路径
func FormatPath(p string) string {
	p = strings.Replace(p, "\\", "/", -1)
	return p
}

func GetExecutable() string {
	p, err := os.Executable()
	if err != nil {
		panic(err)
	}

	p = path.Dir(p)
	p = FormatPath(p)
	return p
}
